package pr1.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Login extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel panel;
	private JTextField user;
	private JLabel userLabel;
	private JPasswordField password;
	private JLabel passwordLabel;
	private JButton entrar;
	private JButton nuevoUsuario;
	private GUIController gui;

	public Login(GUIController gui) {
		super("Login");
		this.gui = gui;
		build();

	}

	private void build() {
		panel = new JPanel();
		this.setPreferredSize(new Dimension(300, 150));
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.add(panel);
		panel.setLayout(null);

		userLabel = new JLabel("Nick");
		userLabel.setBounds(10, 10, 80, 25);
		panel.add(userLabel);

		user = new JTextField(20);
		user.setBounds(100, 10, 160, 25);
		panel.add(user);

		passwordLabel = new JLabel("Contraseña");
		passwordLabel.setBounds(10, 40, 80, 25);
		panel.add(passwordLabel);

		password = new JPasswordField(20);
		password.setBounds(100, 40, 160, 25);
		panel.add(password);

		entrar = new JButton("Entrar");
		entrar.setBounds(10, 80, 80, 25);
		panel.add(entrar);

		entrar.addActionListener(new EntrarListener());

		nuevoUsuario = new JButton("Nuevo usuario");
		nuevoUsuario.addActionListener(new NuevoUsuarioListener());
		nuevoUsuario.setBounds(153, 80, 120, 25);
		panel.add(nuevoUsuario);
		pack();
		this.setVisible(true);
		this.setLocationRelativeTo(null);

	}

	private class EntrarListener implements ActionListener {

		@SuppressWarnings("deprecation")
		@Override
		public void actionPerformed(ActionEvent arg0) {
			if (!gui.login(user.getText(), password.getText())) {
				JOptionPane.showMessageDialog(new JFrame(),
						"Datos incorrectos", "Error",
						JOptionPane.ERROR_MESSAGE, null);
			}
		}

	}
	
	private class NuevoUsuarioListener implements ActionListener{

		@SuppressWarnings("deprecation")
		@Override
		public void actionPerformed(ActionEvent e) {
			
			if (!gui.nuevoUsuario(user.getText(), password.getText())) {
				JOptionPane.showMessageDialog(new JFrame(),
						"No ha sido posible registrarse", "Error",
						JOptionPane.ERROR_MESSAGE, null);
			}
			
		}
		
	}

}
